#include "MainWindow.h"
//----------------------------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>	Includes done in cpp file to accelerate compilation.
//----------------------------------------------------------------------------------------
#include <QInputDialog>
#include <QDebug>
#include <QDomDocument>
#include <QFileDialog>



//----------------------------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>	Constructor/Destructor
//----------------------------------------------------------------------------------------
MainWindow::MainWindow(QWidget *parent)
:QMainWindow(parent)
{
	ui.setupUi(this);
	connect(ui.loc_connect, SIGNAL(pressed()), this, SLOT(connectDB()));
	connect(ui.ext_fileBrowse, SIGNAL(pressed()), this, SLOT(browseFile()));
	connect(ui.ext_fileSave, SIGNAL(pressed()), this, SLOT(saveToFile()));
	connect(ui.central_toBu, SIGNAL(pressed()), this, SLOT(toXml()));
	connect(ui.central_fromBu, SIGNAL(pressed()), this, SLOT(toDb()));

	ui.loc_tabWgt->setColumnWidth(0,250);
	ui.loc_tabWgt->setColumnWidth(1,30);
	ui.loc_tabWgt->setColumnWidth(2,50);
	ui.loc_tabWgt->setColumnWidth(3,20);

	ui.ext_tabWgt->setColumnWidth(0,250);
	ui.ext_tabWgt->setColumnWidth(1,30);
	ui.ext_tabWgt->setColumnWidth(2,50);
	ui.ext_tabWgt->setColumnWidth(3,20);


}

MainWindow::~MainWindow()
{
}





//----------------------------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>	Private SLOTS
//----------------------------------------------------------------------------------------

bool MainWindow::connectDB()
{
	if(!m_DB.isOpen()) {

		m_DB = QSqlDatabase::addDatabase("QMYSQL");

		bool ret;


		QString db_host = "localhost";
		QString db_port = "3306";
		QString db_user = "amarokuser";
		QString db_pass = "amarok";

		QString db_name = "amarokdb";

		m_DB.setHostName(db_host);
		m_DB.setDatabaseName(db_name);
		m_DB.setPort(db_port.toInt());
		m_DB.setUserName(db_user);
		m_DB.setPassword(db_pass);

		ret = m_DB.open();
		if(ret==false)
		{
			qWarning() << "Can not connect to database="<< m_DB.databaseName() <<" with user=" << m_DB.userName() << ", password="<< m_DB.password() << ", host=" << m_DB.hostName();
			qWarning() <<  m_DB.lastError() << "(type=" << m_DB.lastError().type() << ")";
			return false;
		}
	}
	qDebug() << "Database is connected";
	ui.loc_connect->setText("Refresh");
	retrieveDBRatings();
	displayRateItems(ui.loc_tabWgt,listDb);

	return true;
}


bool MainWindow::browseFile()
{
	QFileInfo fInfo;
	QString fileName = QFileDialog::getSaveFileName(
			this, tr("Select Xml File"),
			"",
			tr("Xml Files (*.xml);;All Files (*.*)"));


	fInfo = QFileInfo(fileName);
	if(fInfo.exists()) retrieveFile();

	ui.ext_filePath->setText(fileName);
}


bool MainWindow::retrieveFile()
{

}



bool MainWindow::retrieveDBRatings()
{
	if(!m_DB.isOpen()) {
		qWarning() << "Database is not connected";
		return false;
	}


	//Prepare SQL query according to the type of query.
	QSqlQuery query;
	QString qStr = "SELECT statistics.url, artists.name, albums.name, tracks.title, statistics.rating "
			"FROM statistics, tracks, artists, albums "
			"WHERE rating != '0' "
			"AND statistics.url = tracks.url "
			"AND artists.id = tracks.artist "
			"AND albums.id=tracks.album "
			"ORDER BY albums.name ASC, tracks.tracknumber ASC;";


	if(!query.exec(qStr))
	{
		qWarning() << query.lastError();
	}
	else {
		if(query.size()==0)
		{
			qWarning() << "No response from query";
		}


		//Clear the list
		listDb.clear();

		int row=0;
		while (query.next()) {

			//Create a rating item
			RatingItem rItem;
			rItem.url=query.value(0);
			rItem.artist=query.value(1).toString();
			rItem.album=query.value(2).toString();
			rItem.title=query.value(3).toString();
			rItem.rate=query.value(4).toInt();

			//Add item to the list
			listDb.push_back(rItem);


			row++;
		}

	}

	return query.last();
}


bool MainWindow::saveToFile()
{
	QList<RatingItem>& listRates=listDb;
	QFileInfo fileXml(ui.ext_filePath->text());

	if(fileXml.absoluteDir().exists()==false)
	{
		qWarning() << fileXml.absoluteDir() << "is not a valid directory";
		return false;
	}

	QFile file(fileXml.absoluteFilePath());
	 if (!file.open(QIODevice::WriteOnly))  {
		 qWarning() << fileXml.absoluteDir() << "could not open the file in write mode";
		 return false;
	 }




	QDomDocument xmlDoc(fileXml.fileName());
	QDomElement rootEl = xmlDoc.createElement("root");
	xmlDoc.appendChild(rootEl);


	QDomElement items = xmlDoc.createElement("ratingItems");
	items.setAttribute("number",listRates.size());
	rootEl.appendChild(items);


	for(int row=0;row<listRates.size();row++)
	{
		RatingItem rItem = listRates[row];

		QDomElement itemEl = xmlDoc.createElement("item");
		itemEl.setAttribute("id",rItem.id.toString());
		itemEl.setAttribute("url",rItem.url.toString());
		itemEl.setAttribute("artist",rItem.artist);
		itemEl.setAttribute("album",rItem.album);
		itemEl.setAttribute("title",rItem.title);
		itemEl.setAttribute("rate",QString::number(rItem.rate));

		items.appendChild(itemEl);
	}

	//Write the document in the file
	QTextStream out(&file);
	out << xmlDoc.toString();

	qDebug() << "Correctly written "<<listRates.size() << "items";


}


bool MainWindow::toXml()
{

	if(!listDb.empty())
	{
		if(listXml.empty())
		{
			listXml.append(listDb);
		}
		else
		{
			qWarning() << "Not implemented";
		}

		displayRateItems(ui.ext_tabWgt,listXml);
	}


}

bool MainWindow::toDb()
{

}



void MainWindow::displayRateItems(QTableWidget *tabWgt, const QList<RatingItem>& listRates)
{
	tabWgt->setRowCount(listRates.size());

	for(int row=0;row<listRates.size();row++)
	{
		RatingItem rItem = listRates[row];

		//Column 1
		QTableWidgetItem *itName = new QTableWidgetItem(rItem.artist+" - "+rItem.album + "-" + rItem.title);
		itName->setData(Qt::UserRole,rItem.url);
		tabWgt->setItem(row, 0, itName);

		//Column 2
		QTableWidgetItem *itRate = new QTableWidgetItem(QString::number(rItem.rate));
		tabWgt->setItem(row, 1, itRate);

		//Column 3
		QTableWidgetItem *itCheck = new QTableWidgetItem("");
		itCheck->setCheckState(Qt::Checked);
		tabWgt->setItem(row, 3, itCheck);
	}
}



